package com.yifeng.repo.base.utils.common;

import java.util.Collection;

/**
 * Created by daibing on 2021/11/21.
 */
public class FirePreconditions {

    public static void checkState(boolean expression, String errorMessage) {
        if (!expression) {
            throw new RuntimeException(errorMessage);
        }
    }

    public static void checkState(boolean expression,  ErrorHandler handler) {
        if (!expression) {
            throw handler.newCheckException();
        }
    }

    public static <T> T checkNotNull(T reference, String errorMessage) {
        if (reference == null) {
            throw new RuntimeException(errorMessage);
        }
        return reference;
    }

    public static <T> T checkNotNull(T reference, ErrorHandler handler) {
        if (reference == null) {
            throw handler.newCheckException();
        }
        return reference;
    }

    public static void checkNotEmpty(Collection<?> collection, String errorMessage) {
        if (isEmptyCollection(collection)) {
            throw new RuntimeException(errorMessage);
        }
    }

    public static void checkNotEmpty(Collection<?> collection, ErrorHandler handler) {
        if (isEmptyCollection(collection)) {
            throw handler.newCheckException();
        }
    }

    public static void hasText(String text, String errorMessage) {
        if (isEmptyText(text)) {
            throw new RuntimeException(errorMessage);
        }
    }

    public static void hasText(String text, ErrorHandler handler) {
        if (isEmptyText(text)) {
            throw handler.newCheckException();
        }
    }

    private static boolean isEmptyArray(Object[] array) {
        return array == null || array.length == 0;
    }

    private static boolean isEmptyCollection(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    private static boolean isEmptyText(String str) {
        return str == null || str.isEmpty();
    }

    public interface ErrorHandler {
        RuntimeException newCheckException();
    }
}
